<script setup>

import { ref, onMounted } from 'vue';

const score = ref(0);
const coins = ref(0);
const lives = ref(3);

const startScreen = ref(null);
const gameOverScreen = ref(null);
const winScreen = ref(null);
const gameContainer = ref(null);

const player = ref(null);
const platforms = ref([]);

let gameRunning = false;
let keysPressed = {};
let playerX = 30;
let playerY = 300;
let playerVelocityX = 0;
let playerVelocityY = 0;
let gravity = 0.5;
let gameLoopId;

function jump() {
  playerVelocityY = 15;
}

document.addEventListener('keydown', (e) => {
  keysPressed[e.key] = true;
  if (e.key === ' ') {
    jump();
  }
});

document.addEventListener('keyup', (e) => {
  keysPressed[e.key] = false;
});

function startGame() {
  // Reset game state
  score.value = 0;
  coins.value = 0;
  lives.value = 3;
  // level = 1;
  // playerX = 50;
  // playerY = 300;
  // playerVelocityY = 0;
  // playerVelocityX = 0;
  // isJumping = false;
  // cameraOffset = 0;
  // gameSpeed = 3;

  // Hide screens
  startScreen.value.classList.add('hidden');
  gameOverScreen.value.classList.add('hidden');
  winScreen.value.classList.add('hidden');

  // 根据关卡初始化游戏元素
  // 包括平台，金币，敌人等等
  setupLevel(1)

  // Start game loop
  gameRunning = true;
  gameLoopId = requestAnimationFrame(gameLoop);
}

function setupLevel(level) {
  // Ground platform
  createPlatform(0, 0, 2000, 40);

  if (level === 1) {
    createPlatform(200, 100, 150, 20);
    createPlatform(400, 200, 150, 20);
    createPlatform(600, 150, 150, 20);
    createPlatform(800, 250, 150, 20);
    createPlatform(1000, 180, 150, 20);
  }
}

function createPlatform(x, y, width, height) {
  // const platform = document.createElement('div');
  // platform.className = 'platform';
  // platform.style.left = x + 'px';
  // platform.style.bottom = y + 'px';
  // platform.style.width = width + 'px';
  // platform.style.height = height + 'px';
  // gameContainer.value.appendChild(platform);
  // console.log(gameContainer.value);

  platforms.value.push({
    // element: platform,
    x: x,
    y: y,
    width: width,
    height: height
  });

  console.log(platforms.value);
}

function checkCollisions() {
  const playerBottom = playerY;
  const playerTop = playerY + 60;
  const playerLeft = playerX;
  const playerRight = playerX + 40;
  
  let isCollide = false;
  let currTop = 0;
  for (const platform of platforms.value) {
    const platformTop = platform.y + platform.height;
    const platformBottom = platform.y;
    const platformLeft = platform.x;
    const platformRight = platform.x + platform.width;

    if (playerBottom <= platformTop &&
      playerTop >= platformBottom &&
      playerLeft <= platformRight &&
      playerRight >= platformLeft
    ) {
      isCollide = true;
      currTop = platformTop;
    }
  }

  if (isCollide) { 
    playerVelocityY = 0;
    playerY = currTop+1;
  } else {
    playerVelocityY -= gravity;
  }
}

function gameLoop() {
  if (!gameRunning) return;

  // Handle player movement
  if (keysPressed['ArrowRight'] || keysPressed['d']) {
    playerVelocityX = 5;
  } else if (keysPressed['ArrowLeft'] || keysPressed['a']) {
    playerVelocityX = -5;
  } else {
    playerVelocityX = 0;
  }

  // Check collisions
  checkCollisions();

  console.log(playerVelocityY);
  playerX += playerVelocityX;
  playerY += playerVelocityY;

  // Keep player in bounds
  if (playerX < 0) playerX = 0;

  player.value.style.left = `${playerX}px`;
  player.value.style.bottom = `${playerY}px`;
  // console.log(`Player X: ${playerX}`);
  //player.value.style.transform = `translateX(${playerX}px)`;

  // Continue game loop
  gameLoopId = requestAnimationFrame(gameLoop);
}

</script>

<template>
  
<div class="bg-gray-900 flex flex-col items-center justify-center min-h-screen p-4">
  <h1 class="text-4xl font-bold text-white mb-4">横版闯关游戏</h1>

  <div class="game-container mb-4" id="gameContainer" ref="gameContainer">
    <div class="player" id="player" ref="player"></div>

    <div class="game-overlay" id="startScreen" ref="startScreen">
      <h2 class="text-4xl font-bold text-white mb-6">Super Adventure</h2>
      <p class="text-xl text-white mb-8">Use arrow keys to move and space to jump</p>
      <button 
        id="startButton" 
        class="bg-green-500 hover:bg-green-600 text-white font-bold py-3 px-6 rounded-full text-xl transition duration-300 transform hover:scale-105"
        @click="startGame"
      >
          Start Game
      </button>
    </div>

    <div class="game-overlay hidden" id="gameOverScreen" ref="gameOverScreen">
      <h2 class="text-4xl font-bold text-white mb-6">Game Over</h2>
      <p class="text-xl text-white mb-4">Score: <span id="finalScore">0</span></p>
      <p class="text-xl text-white mb-8">Coins Collected: <span id="finalCoins">0</span></p>
      <button id="restartButton" class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-3 px-6 rounded-full text-xl transition duration-300 transform hover:scale-105">
          Play Again
      </button>
    </div>

    <div class="game-overlay hidden" id="winScreen" ref="winScreen">
      <h2 class="text-4xl font-bold text-white mb-6">Level Complete!</h2>
      <p class="text-xl text-white mb-4">Score: <span id="winScore">0</span></p>
      <p class="text-xl text-white mb-8">Coins Collected: <span id="winCoins">0</span></p>
      <button id="nextLevelButton" class="bg-yellow-500 hover:bg-yellow-600 text-white font-bold py-3 px-6 rounded-full text-xl transition duration-300 transform hover:scale-105">
          Next Level
      </button>
    </div>

    <div v-for="(p, i) in platforms" 
      :key="i"
      :style="{left: p.x + 'px',
        bottom: p.y + 'px',
        width: p.width + 'px',
        height: p.height + 'px'}"
      class="platform">
    </div>

    <!-- <div class="platform" style="left: 0px;bottom: 0px;width: 2000px;height: 100px;"></div> -->
  </div>

  <div class="bg-gray-800 p-4 rounded-lg w-full max-w-md">
    <div class="flex justify-between items-center mb-2">
      <div class="text-white text-xl">
          Score: {{ score }}
      </div>
      <div class="text-white text-xl">
          Coins: {{ coins }}
      </div>
    </div>
    <div class="text-white text-lg">
        Lives: {{ lives }}
    </div>
  </div>
</div>

</template>

<style scoped>
.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}
.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}

.game-container {
  position: relative;
  width: 800px;
  height: 400px;
  overflow: hidden;
  background: linear-gradient(to bottom, #87CEEB 50%, #5cb85c 50%);
  border: 4px solid #333;
  border-radius: 8px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
}

.player {
  position: absolute;
  width: 40px;
  height: 60px;
  background-color: #e74c3c;
  border-radius: 8px;
  transition: transform 0.1s;
  z-index: 10;
}

.player::after {
  content: '';
  position: absolute;
  bottom: -5px;
  left: 5px;
  width: 30px;
  height: 10px;
  background-color: #333;
  border-radius: 50%;
}

.game-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 100;
}

.hidden {
  display: none;
}

.platform {
  position: absolute;
  background-color: #8B4513;
  border: 2px solid #5D4037;
  border-radius: 4px;
  z-index: 10;
}

</style>
